<template>
	<view>
		<web-view :src="src" v-if="src" @message="handleWebMsg"></web-view>
	</view>
</template>

<script setup lang="ts">
import { ref, nextTick } from 'vue';
import { useLayout,useUser } from '@/common/stores';
import { storeToRefs } from 'pinia';
import { onLoad } from '@dcloudio/uni-app';
import { useCurrentInstance } from '@/common/hooks';
import { sys } from '@/common/utils';

const ctx = useCurrentInstance();
const userStore = useUser();
const { otherUrl } = storeToRefs(useLayout());

const src = ref('');

const handleWebMsg = (e: { detail: { data: any[] } }) => {
	// #ifdef APP
	let data = e.detail.data[0];
	if (data.name === 'scanCode') {
		uni.scanCode({
			success: (res) => {
				const currentWebview = (ctx as any)?.$scope?.$getAppWebview();
				const wv = currentWebview.children()[0];
				wv.evalJS(`scanCodeCallback('${res.result}')`);
			}
		});
	} else if (data.name === 'loginOut') {
		userStore.outLogin();
		ctx.$goLogin();
	} else if (data.name === 'saveImg') {
		console.log(data.params)
	}else if (data.name === 'h5PullAppPay') {
		uni.sendNativeEvent(
			'pullAppPay',
			data.params
		);
	}
	// #endif
};

onLoad((opt: { url?: string }) => {
	const system = sys();
	if (opt.url) {
		if (otherUrl.value) {
			src.value = otherUrl.value;
			// #ifdef APP
			nextTick(() => {
				const currentWebview = (ctx as any)?.$scope?.$getAppWebview();
				setTimeout(() => {
					const wv = currentWebview.children()[0];
					let js = `var script = document.createElement("script");
					script.type = "text/javascript";
					script.src = "https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js"
					document.getElementsByTagName("head")[0].appendChild(script);`;
					const emits = ['scanCode', 'saveImg', 'loginOut','h5PullAppPay'];
					if (system.platform === 'android') {
						js += `window.android = {${emits
							.map(
								(item) => `${item}:function (...args){
							uni.postMessage({
								data:{
										name:'${item}',
										params:args
									}
								}
						)
						}`
							)
							.join(',')}};`;
					} else {
						js += `window.webkit = {
							messageHandlers: {
								${emits
									.map(
										(item) => `${item}:{
									postMessage: function (...args){
										uni.postMessage({
											data:{
												name:'${item}',
												params:args
											}
										});
									}
								}`
									)
									.join(',')}
							}
						}`;
					}
					wv.evalJS(js);
				}, 1000);
			});
			// #endif
		} else {
			src.value = opt.url;
		}
	} 
});
</script>

<style></style>
